/**
 * @author GhostWei
 */
var _ajax = {
	id: 'list',
	loading: 'Loading...',
	url: '/list',
	name: 'name',
	form: '',
	error: function(msg) {
		this.id.html('Error: ' + msg);
	},
	load: function(pid) {
		var page = typeof(pid) == 'undefined' ? 1 : parseInt(pid);
		$('#check-all').removeAttr('checked');
		this.id.html(this.loading);
		var data = [];
		data.push('page=' + page);
		data.push('r=' + Math.random().toString().replace('.', '_'));
		var _data = data.join('&') + '&' + this.formData().join('&');
		var self = this;
		$.ajax({type:'POST',dataType:'json',url:this.url,data:_data,success:function(json, status){
			try {
				if(json.status == 0) {
					throw json;
				}
				if(typeof(json.html) == 'undefined') {
					self.error('Load Data failed.');
				} else {
					self.id.html(json.html);
					$("#" + self.name + "-id-x option").each(function(){
						var id = $(this).val();
						$('#_' + self.name + '_id-' + id).attr('checked', 'checked');
					});
				}
			} catch (e) {
				self.error(e.message);
			}
		}, error: function (req, msg, e) {
			self.error(req['statusText']);
		}, timeout: 30000});
		return false;
	},
	formData: function() {
		var params = this.form.serializeArray();
		var rst = [];
		for(var i in params) {
			rst.push(params[i]['name'] + '=' + encodeURIComponent(params[i]['value']));
		}
		return rst;
	},
	select: function(id) {
		var cbox = $('#_' + this.name + '_id-' + id);
		if(!cbox.attr('checked')) {
			$("#" + this.name + "-id-x option[value='" + id + "']").remove();
			this.selectAll();
			return;
		}
		var text = $('#' + this.name + '-title-' + id).text();
		$("#" + this.name + "-id-x option[value='" + id + "']").remove();
		$('#' + this.name + '-id-x').append('<option value="' + id + '">' + text + '</option>');
		this.selectAll();
	},
	selectAll: function() {
		$("#" + this.name + "-id-x option").each(function(){
			$(this).attr('selected', 'selected');
		});
	},
	checkAll: function(c) {
		var checked = !c.checked;
		var self = this;
		$('#' + this.name + '-list').find('input[type=checkbox]').each(function(){
			if(checked) {
				$(this).attr('checked', 'checked');
			} else {
				$(this).removeAttr('checked');
			}
			self.select($(this).val());
		});
	}
};

